#include "RC522.h" //RC522模块所需头文件
#include <SPI.h>
#include <string.h>
#include <math.h>

const int pinRelay1 = 8;//继电器
const int pinRelay4 = 7;//蜂鸣器
unsigned char serNum[5]; //ic卡的id码
int decid = 0;
int i = 0;
int relayState = 0;
int s1 = 0;
int s2 = 2;
int s3 = 0;

void setup()
{
    Serial.begin(9600);
    Serial.println("welcome!");
    SPI.begin();

    pinMode(chipSelectPin, OUTPUT);
    digitalWrite(chipSelectPin, LOW);
    pinMode(NRSTPD, OUTPUT);
    MFRC522_Init();
    pinMode(pinRelay1, OUTPUT); 
    pinMode(pinRelay4, OUTPUT);   
}

int time = 0;

void loop() //持续检测是否感应到ic卡
{
    decid = 0;
    digitalWrite(pinRelay1, LOW);
    s1 = 0;
    
    unsigned char status; //状态变量
    unsigned char str[MAX_LEN];
    status = MFRC522_Request(PICC_REQIDL, str); //传入卡状态，2为无卡，0为感应到卡
    if (status == MI_OK)      //读取到ID卡时候，MI_OK=0
    {   
      status = MFRC522_Anticoll(str);    
      if (status == MI_OK)    //下一个时刻仍能读取到ID卡
      {
          memcpy(serNum, str, 5);
          Serial.print("ID:");  
          ShowCardID(serNum);   //输出卡ID，16进制
          
          unsigned char* id = serNum;
          
          for(i=0;i<4;i++){  
            decid=decid+id[i]*pow(16,i);    //16转10进制
          }
          Serial.print("DECID:");
          Serial.println(decid);   //输出卡DECID，10进制

          switch(decid){
            
               case -XXXXX://cade //允许通过的卡ID(电门)
               case 123456: //使用读卡程序读出来的10进制的卡号替换XXXXX
               case XXXXX:
               case -XXXXXX:
               //若需要添加新卡，在此处新添加一个case XXXX:
                 Serial.println("Pass!");
                 digitalWrite(pinRelay1, HIGH); //继电器开
                 digitalWrite(pinRelay4, HIGH); //蜂鸣器响0.5秒
                 delay(1000); //暂停1秒
                 digitalWrite(pinRelay4, LOW);                                   
                 digitalWrite(pinRelay1, LOW); //继电器关
                 Serial.println("off!");
                 delay(1000); //暂停1秒
                 break;  //跳出case        
             default:   //如果不在允许的ID中
                               
                if(s3==60){
                  Serial.println("Strange Card");
                  delay(30000); //暂停30秒
                }else{
                   Serial.println("no card");
                   s3++;
                   Serial.println (s3);
                  delay(1000); //暂停1秒
                }                  
             break;  //跳出default
          }
      }
    }
    MFRC522_Halt();
    delay(500);   //每0.5s检测一次
}
